package com.beida.redistest.controller;

import com.beida.redistest.config.Result;
import com.beida.redistest.domain.po.User;
import com.beida.redistest.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2024-08-26
 */
@RestController
@RequestMapping("/user")
@Api
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Resource
    private  IUserService userService;
    @Resource
    private  RedisTemplate redisTemplate;

    public static final String CACHE_KEY_USER = "user:";
    public static final String CACHE_NAME_USER_LIST = "userList";

    // 查询所有用户
    @GetMapping("/userList")
    @Cacheable(value = CACHE_NAME_USER_LIST, key = "'allUsers'", unless = "#result != null && !#result.isEmpty()")
    @ApiOperation("查询所有用户")
    public Result<List<User>> findAll() {
        // 假设userService.list()是从数据库或其他数据源获取用户列表
        List<User> userList = userService.list();

        // 将用户列表中的每个用户存储到Redis中
        for (User user : userList) {
            String cacheKey = CACHE_KEY_USER + user.getId();
            redisTemplate.opsForValue().set(cacheKey, user);
        }

        return Result.success(userList);
    }

    @ApiOperation(value = "新增用户")
    @PostMapping("/save")
    @CachePut(value = CACHE_NAME_USER_LIST, key = "'allUsers'")
    public Result save(@RequestBody User user) {
        boolean success = userService.save(user);
        if (success) {
            String key = CACHE_KEY_USER + user.getId();
            redisTemplate.opsForValue().set(key, user);
            log.info("用户已保存并存入缓存: {}", user);
        }
        return Result.success();
    }

    @ApiOperation(value = "更新用户")
    @PutMapping("/update")
    @CachePut(value = CACHE_NAME_USER_LIST, key = "'allUsers'")
    public Result update(@RequestBody User user) {
        boolean success = userService.updateById(user);
        if (success) {
            String key = CACHE_KEY_USER + user.getId();
            redisTemplate.opsForValue().set(key, user);
            log.info("用户已更新并存入缓存: {}", user);
        }
        return Result.success();
    }

    @ApiOperation(value = "删除用户")
    @DeleteMapping("/delete/{id}")
    @CacheEvict(value = CACHE_NAME_USER_LIST, key = "'allUsers'")
    public Result delete(@PathVariable Integer id) {
        boolean success = userService.removeById(id);
        if (success) {
            String key = CACHE_KEY_USER + id;
            redisTemplate.delete(key);
            log.info("用户已删除并清除缓存: {}", id);
        }
        return Result.success();
    }

    @ApiOperation(value = "根据id查询用户")
    @GetMapping("/findById/{id}")
    @Cacheable(value = CACHE_NAME_USER_LIST, key = "#id", unless = "#result == null")
    public Result<User> findById(@PathVariable Integer id) {
        String key = CACHE_KEY_USER + id;
        User user =(User) redisTemplate.opsForValue().get(key);

        if (user == null) {
            user = userService.selectbyid(id);
            if (user == null) {
                return Result.error("用户不存在");
            }
            redisTemplate.opsForValue().set(key, user);
        }

        return Result.success(user);
    }
}